<?php

$logFilePath = "log.txt";
$kmlFilePath = "kml.xml";
// Create a simple array.
/*
"smart-distance-based-with-acc" red, "simple" yellow, "distanced-based" green,
      "configurable-maximum-speed" blue,
      "distanced-based-with-accelerometer" purple
*/
//Generating valid KML according to :http://www.kmlvalidator.com/validate.htm
$typeColorArray = array("smart-distance-based-with-acc"=>"FFFF0000", "periodic"=>"FFFBFF00", "distanced-based"=>"FF00FF04", "configurable-maximum-speed"=>"FF0011FF", "distanced-based-with-accelerometer"=>"FFFF00EE");

if(checkPostRequest()) {
	?>
	<html>
		<body>
			<form action='' method="POST">
				<input type="text" name="longitude"> long<br/>
				<input type="text" name="latitude"> lat <br/>
				<input type="text" name="altitude"> alt <br/>
				<input type="text" name="timestamp"> ts <br/>
				<input type="text" name="type"> type <br/>
				<input type="submit" name="submit"> <br/>
			</form>	
		</body>
	</html>
	<?php
}
else {
	$longitude = $_POST['longitude'];
	$altitude = $_POST['altitude'];
	$latitude = $_POST['latitude'];
	$timestamp = $_POST['timestamp'];
	$timestamp = $timestamp/1000;
	$typeStrategy = $_POST['type'];

	$kmlFilePath = "data/".$typeStrategy."-".$kmlFilePath;
	$logFilePath = "data/".$typeStrategy."-".$logFilePath;
	
	writeToLog($logFilePath, $timestamp);
	$xml;	
	//file does not exist yet, write the root element!
	if(!file_exists($kmlFilePath)) {
		$xml = new DOMDocument("1.0");
		//root element : <kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2">
		$root = $xml->createElement("kml");
		//set namespace attribute
		$xmls = $xml->createAttribute("xmlns");
		$root->appendChild($xmls);
		$xmlsValue = $xml->createTextNode("http://www.opengis.net/kml/2.2");
		$xmls->appendChild($xmlsValue);

		$xml->appendChild($root);
		$documentElement = $xml->createElement("Document");
		$root->appendChild($documentElement);
		
		//write the styleElements for each pin type to use later when placemarkers are created
		foreach ($typeColorArray as $type => $color) {
			$style = $xml->createElement("Style");
				$styleId = $xml->createAttribute("id");
					$styleIdValue = $xml->createTextNode($type);
				$styleId->appendChild($styleIdValue);
			$style->appendChild($styleId);
			
				$iconStyle = $xml->createElement("IconStyle");
					
					$colorElement = $xml->createElement("color");
						$colorElementText = $xml->createTextNode($color);
					$colorElement->appendChild($colorElementText);
				$iconStyle->appendChild($colorElement);				
					
					$iconElement = $xml->createElement("Icon");
						$hrefElement = $xml->createElement("href");
							$hrefElementText = $xml->createTextNode("http://maps.google.com/mapfiles/kml/pushpin/wht-pushpin.png");			
						$hrefElement->appendChild($hrefElementText);
					$iconElement->appendChild($hrefElement);
				$iconStyle->appendChild($iconElement);
			$style->appendChild($iconStyle);
			
			$documentElement->appendChild($style);
		}
	}
	//file have been created, load the xmlfile
	else {
		$xml = new DOMDocument();
		$xml->load($kmlFilePath);
	}
	$nodes = $xml->getElementsByTagName('Document') ;
	if ($nodes->length > 0) {
		//the first element is the kml element
//		$kmlnode = $nodes->item(0);
//		$documentNodes = $kml->getElementsByTagName('Document');
		$documentElement = $nodes->item(0);
			
		$placemarker = $xml->createElement("Placemark");
		
		$name = $xml->createElement("name");
//			$nameText = $xml->createTextNode($typeStrategy);
	//		$name->appendChild($nameText);		
		$placemarker->appendChild($name);

		$description = $xml->createElement("description");
			$descriptionText = $xml->createTextNode($longitude.", ".$altitude.", ".$latitude);
			$description->appendChild($descriptionText);		
		$placemarker->appendChild($description);
		
				//add timestamp
	//	<TimeStamp>
  			//<when>1997-07-16T10:30:15+03:00</when>
	  //</TimeStamp>
		
		$timeStampElement = $xml->createElement("TimeStamp");
			$when = $xml->createElement("when");
				$whenText = $xml->createTextNode(convertTime($timestamp));
			$when->appendChild($whenText);
			$timeStampElement->appendChild($when);
		$placemarker->appendChild($timeStampElement);	
		
		//styleUrl sets color of pin
		//<styleUrl>#myDefaultStyles</styleUrl>
		
		$styleUrl = $xml->createElement("styleUrl");
			$styleUrlText = $xml->createTextNode("#".$typeStrategy);
			$styleUrl->appendChild($styleUrlText);		
		$placemarker->appendChild($styleUrl);

		$point = $xml->createElement("Point");
		$placemarker->appendChild($point);
			$coordinates = $xml->createElement("coordinates");
				$coordinatesText = $xml->createTextNode($longitude.",".$latitude.",".$altitude); //long, lat, alt 
				$coordinates->appendChild($coordinatesText);		
			$point->appendChild($coordinates);
			
		$documentElement->appendChild($placemarker);
	}
	//save
	$xml->save($kmlFilePath);
	
	//debug output from xml.
	header("Content-Type: text/plain");
	echo $xml->saveXML();
}

function writeToLog($logFilePath, $timestamp) {
	//opens the file with pointer at the end. If file does not exist, the file i created
	$logHandle = fopen($logFilePath, 'a');
	$lines = count(file($logFilePath));
	fwrite($logHandle, ($lines+1)." : ".$timestamp."\n");
	fclose($logHandle);
}

function checkPostRequest() {
	if(!isset($_POST['longitude'], $_POST['latitude'], $_POST['timestamp'], $_POST['type'], $_POST['altitude'])) {
		if($_POST['timestamp'] !== "") {
			//echo "one or more attributes not defined";
			return true;
		}
	}
	return false;
}

function convertTime($ts) {
	//YYYY-MM-DDThh:mm:ssZ
	$date = date("Y-m-d", $ts);
	$time = date("H:i:s", $ts);
	
	return 	$date."T".$time."Z";

}

?>